package com.yixun.qfbao.utils;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.yixun.qfbao.mapper.SubscriptionMapper;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;

/**
 * 注释添加  zilong.liu
 * 方法千万不要随便用。
 *app_id和 secret的来源有误
 */
@Component
public class WeAppUtils {
	
	@Autowired
	SubscriptionMapper subscriptionMapper;

    private static Logger logger = LoggerFactory.getLogger(WeAppUtils.class);

    private static final String APP_ID = "wxeb5f69727b1c40fc";

    private static final String SECRET = "c37642cf835440cf3978b89b4b2d32e7";

    private static final HashMap<String, String> GRANT_TYPE_MAP= new HashMap<String, String>(){
        {
            put("jsCode", "authorization_code");
            put("accessToken", "client_credential");
        }
    };

    private static final String JS_CODE_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send";

    /**
     * 获取openId
     */
    public static String getOpenId(String jsCode, String appId, String secret){
    	String realAppId = StringUtils.isBlank(appId)? APP_ID: appId;
    	String realSecret = StringUtils.isBlank(secret)? SECRET: secret;
        if(StringUtils.isBlank(jsCode)){
            throw new RuntimeException("jsCode不能为空");
        }
        String params = "appid=" + realAppId + "&secret=" + realSecret + "&grant_type=" + GRANT_TYPE_MAP.get("jsCode") + "&js_code=" + jsCode;
        JSONObject jsonObject = JSONObject.parseObject(HttpApi.sendGet(JS_CODE_URL, params, null));
        logger.info("weixin jscode result", jsonObject.toJSONString());
        if(null != jsonObject.get("errcode") && !"0".equals(jsonObject.get("errcode"))){
            throw new RuntimeException("获取openid失败:" + jsonObject.getString("errmsg"));
        }
        return jsonObject.getString("openid");
    }
    
    /**
     * 获取openId
     */
    public static JSONObject getWxBindByJsCode(String jsCode, String appId, String secret){
    	String realAppId = StringUtils.isBlank(appId)? APP_ID: appId;
    	String realSecret = StringUtils.isBlank(secret)? SECRET: secret;
        if(StringUtils.isBlank(jsCode)){
            throw new RuntimeException("jsCode不能为空");
        }
        String params = "appid=" + realAppId + "&secret=" + realSecret + "&grant_type=" + GRANT_TYPE_MAP.get("jsCode") + "&js_code=" + jsCode;
        JSONObject jsonObject = JSONObject.parseObject(HttpApi.sendGet(JS_CODE_URL, params, null));
        logger.info("weixin jscode result{}", jsonObject.toJSONString());
        if(null != jsonObject.get("errcode") && !"0".equals(jsonObject.get("errcode"))){
            throw new RuntimeException("获取openid失败:" + jsonObject.getString("errmsg"));
        }
        return jsonObject;
    }

    /**
     * 获取access_token
     */
    public static String getAccessToken(String appId, String secret){
    	String realAppId = StringUtils.isBlank(appId)? APP_ID: appId;
    	String realSecret = StringUtils.isBlank(secret)? SECRET: secret;
        String params = "grant_type=" + GRANT_TYPE_MAP.get("accessToken") + "&appid=" + realAppId + "&secret=" + realSecret;
        JSONObject jsonObject = JSONObject.parseObject(HttpApi.sendGet(ACCESS_TOKEN_URL, params, null));
        if(!"0".equals(jsonObject.get("errcode"))){
            throw new RuntimeException("获取access_token失败:" + jsonObject.get("errmsg").toString());
        }
        return jsonObject.getString("access_token");
    }

    /**
     *  发送模板消息
     */
    public static void sendMessage(String jsonBody, String appId, String secret){
    	String realAppId = StringUtils.isBlank(appId)? APP_ID: appId;
    	String realSecret = StringUtils.isBlank(secret)? SECRET: secret;
        String accessToken = getAccessToken(realAppId, realSecret);
        
        String url = SEND_MESSAGE_URL + "?access_token=" + accessToken;
        JSONObject jsonObject = JSONObject.parseObject(HttpApi.doPost(url, jsonBody));
        if(!"0".equals(jsonObject.get("errcode"))){
            throw new RuntimeException("sendMessage失败:" + jsonObject.get("errmsg").toString());
        }
    }
    
    public Subscription getRealAppIdAndSecret(String systemId, String companyUuid) {
    	if(StringUtils.isBlank(systemId)) {
    		return null;
    	}
    	if(StringUtils.isBlank(companyUuid)) {
    		return null;
    	}
    	SubscriptionDto subscriptionDto = new SubscriptionDto();
    	subscriptionDto.setCompanyUuid(companyUuid);
    	subscriptionDto.setSystemId(systemId);
    	subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
    	logger.info("getRealAppIdAndSecret->companyUuid:{}", companyUuid);
    	logger.info("getRealAppIdAndSecret->systemId:{}", systemId);
    	List<Subscription> subscriptionList = subscriptionMapper.selectListByDto(subscriptionDto);
    	if(CollectionUtils.isEmpty(subscriptionList)) {
    		return null;
    	}
    	logger.info("getRealAppIdAndSecret->subscriptionList:{}", JSON.toJSONString(subscriptionList));
    	return subscriptionList.get(0);
    }
}
